package org.apache.rocketmq.console.config.intercepter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyFilterConfig {
	@Bean
	public LogCostFilter getLogCostFilter() {
		return new LogCostFilter();
	}

	@Bean
	public FilterRegistrationBean registFilter() {
		FilterRegistrationBean registration = new FilterRegistrationBean();
		registration.setFilter(getLogCostFilter());
		registration.addUrlPatterns("/*");
		registration.setName("LogCostFilter");
		registration.setOrder(1);
		return registration;
	}

	class LogCostFilter implements Filter {

		@Override
		public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
				throws IOException, ServletException {
			// 防止流读取一次后就没有了, 所以需要将流继续写出去
			HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
			ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(httpServletRequest);
			filterChain.doFilter(requestWrapper, servletResponse);
		}

		@Override
		public void destroy() {

		}

		@Override
		public void init(FilterConfig filterConfig) throws ServletException {
			System.out.println("filterConfig=============" + filterConfig);

		}

	}
}